/**
 * ESP32 开发辅助工具主入口文件
 * 
 * 项目结构：
 * - components/: UI组件
 * - utils/: 工具函数
 * - assets/: 静态资源
 */

import { AppState } from './utils/state.js';
import { UIManager } from './utils/ui-manager.js';
import { CodeGenerator } from './utils/code-generator.js';
import { FileExporter } from './utils/file-exporter.js';
import { SerialManager } from './utils/serial-manager.js';

class ESP32DevTool {
    constructor() {
        this.state = new AppState();
        this.ui = new UIManager(this.state);
        this.codeGenerator = new CodeGenerator(this.state);
        this.fileExporter = new FileExporter(this.state);
        this.serialManager = new SerialManager(this.state);
        
        this.init();
    }

    init() {
        // 初始化应用
        this.ui.init();
        this.bindEvents();
        this.loadSavedConfig();
        this.generateCode(); // 初始化时生成代码
        
        console.log('ESP32开发辅助工具已初始化');
    }

    bindEvents() {
        // 绑定UI事件
        this.ui.on('chipChange', (value) => {
            // 将芯片型号标准化为UI管理器期望的格式
            let normalizedValue = value.toLowerCase();
            if (normalizedValue.includes('esp32-wroom')) {
                normalizedValue = 'esp32';
            } else if (normalizedValue.includes('esp32-c3')) {
                normalizedValue = 'esp32-c3';
            } else if (normalizedValue.includes('esp32-s2')) {
                normalizedValue = 'esp32-s2';
            } else if (normalizedValue.includes('esp32-s3')) {
                normalizedValue = 'esp32-s3';
            }
            
            this.state.setChipModel(normalizedValue);
            this.ui.updatePinDiagram();
            this.debounceGenerateCode();
        });

        this.ui.on('projectNameChange', (value) => {
            this.state.setProjectName(value);
            this.debounceGenerateCode();
        });

        this.ui.on('featureToggle', (features) => {
            this.state.setFeatures(features);
            this.debounceGenerateCode();
        });

        this.ui.on('pinConfigChange', (config) => {
            // 更新引脚配置
            if (!config || typeof config.type !== 'string') {
                console.warn('收到无效的引脚配置');
                return;
            }

            // 根据配置类型更新状态
            const configTypeHandlers = {
                'led': (pin) => this.state.setLedPin(pin),
                'dht11': (pin) => this.state.setDht11Pin(pin),
                'dht22': (pin) => this.state.setDht22Pin(pin) // 支持新的DHT22传感器类型
            };

            const handler = configTypeHandlers[config.type.toLowerCase()];
            if (handler) {
                handler(config.pin);
            } else {
                console.warn(`不支持的配置类型: ${config.type}`);
            }

            this.debounceGenerateCode();
        });

        this.ui.on('pinConfig', (pin, config) => {
            // 检查config是字符串（旧格式）还是对象（新格式）
            if (typeof config === 'string') {
                // 兼容旧格式，只传mode
                this.state.setPinConfig(pin, { mode: config });
            } else {
                // 新格式，包含mode和description
                this.state.setPinConfig(pin, config);
            }
            this.ui.updatePinDiagram();
            this.debounceGenerateCode();
        });

        this.ui.on('generateCode', () => {
            this.generateCode();
        });

        this.ui.on('downloadProject', () => {
            this.fileExporter.downloadProject();
        });

        this.ui.on('exportText', () => {
            this.fileExporter.exportProjectStructure();
        });

        this.ui.on('connectDevice', async () => {
            try {
                await this.serialManager.connect();
                this.ui.updateConnectionStatus(true);
            } catch (error) {
                this.ui.showAlert('连接设备失败: ' + error.message, 'error');
            }
        });

        this.ui.on('disconnectDevice', async () => {
            try {
                await this.serialManager.disconnect();
                this.ui.updateConnectionStatus(false);
            } catch (error) {
                this.ui.showAlert('断开连接时出错: ' + error.message, 'error');
            }
        });

        this.ui.on('flashFirmware', async (file) => {
            if (!file) {
                this.ui.showAlert('请选择固件文件', 'error');
                return;
            }
            
            try {
                await this.serialManager.flashFirmware(file);
                this.ui.showAlert('固件烧录成功！', 'success');
            } catch (error) {
                this.ui.showAlert('烧录失败: ' + error.message, 'error');
            }
        });

        // 添加ESP-IDF项目导出事件监听器
        this.ui.on('downloadESPProject', () => {
            this.fileExporter.downloadESPProject();
        });

        // 添加Git导出事件监听器
        this.ui.on('exportGit', () => {
            this.fileExporter.exportToGit();
        });

        // 添加库管理器事件监听器
        this.ui.on('openLibraryManager', () => {
            this.ui.openLibraryManager();
        });

        // 添加关闭库管理器事件监听器
        this.ui.on('closeLibraryManager', () => {
            this.ui.closeLibraryManager();
        });
    }

    debounceGenerateCode() {
        clearTimeout(this.debounceTimer);
        this.debounceTimer = setTimeout(() => {
            this.generateCode();
        }, 500);
    }

    generateCode() {
        try {
            const files = this.codeGenerator.generateProject();
            this.state.setProjectFiles(files);
            this.ui.updateCodePreview(files['main/app_main.c']);
            this.ui.updateFileStructureDisplay();
            this.ui.showAlert('代码生成完成', 'success');
        } catch (error) {
            this.ui.showAlert('代码生成失败: ' + error.message, 'error');
            console.error('代码生成失败:', error);
        }
    }

    loadSavedConfig() {
        const savedConfig = localStorage.getItem('esp32_config');
        if (savedConfig) {
            try {
                const config = JSON.parse(savedConfig);
                this.state.loadConfig(config);
                this.ui.loadConfig(config);
            } catch (e) {
                console.error('加载配置时出错:', e);
            }
        }
    }
}

// 应用初始化
document.addEventListener('DOMContentLoaded', () => {
    window.esp32DevTool = new ESP32DevTool();
});

export default ESP32DevTool;